package com.zyx.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyx.security.common.constant.WebSecurityConstant;
import com.zyx.security.common.utils.JsonUtil;
import com.zyx.security.model.base.CommonResult;
import com.zyx.security.service.impl.DaoUserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;

/**
 * <p>自定义WebSecurityConfigurerAdapter</p>
 *
 * @author Yaxi.Zhang
 * @since 2022/9/18 09:19
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final DaoUserDetailServiceImpl daoUserDetailService;

    @Autowired
    public SecurityConfig(DaoUserDetailServiceImpl daoUserDetailService, ObjectMapper objectMapper) {
        this.daoUserDetailService = daoUserDetailService;
    }

    // @Bean
    // public UserDetailsService userDetailsService() {
    //     InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
    //     inMemoryUserDetailsManager.createUser(User.withUsername("root").password("{noop}123").roles("admin").build());
    //     return inMemoryUserDetailsManager;
    // }

    /**
     * 覆盖AuthenticationManager
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // auth.userDetailsService(userDetailsService());
        auth.userDetailsService(daoUserDetailService);
    }

    /**
     * 暴露工厂内部的AuthenticationManager
     */
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    // 自定义 filter 交给工厂管理
    @Bean
    public LoginFilter loginFilter() throws Exception {
        LoginFilter loginFilter = new LoginFilter();
        loginFilter.setFilterProcessesUrl(WebSecurityConstant.FILTER_PROCESSES_URL);
        loginFilter.setUsernameParameter(WebSecurityConstant.USERNAME_PARAMETER);
        loginFilter.setPasswordParameter(WebSecurityConstant.PASSWORD_PARAMETER);
        loginFilter.setAuthenticationManager(authenticationManagerBean());
        // 认证成功处理
        loginFilter.setAuthenticationSuccessHandler((req, resp, auth) -> {
            CommonResult<Object> result = CommonResult.success(auth.getPrincipal());
            resp.setStatus(HttpStatus.OK.value());
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().println(JsonUtil.toJsonString(result));
        });
        // 认证失败处理
        loginFilter.setAuthenticationFailureHandler((req, resp, ex) -> {
            CommonResult<String> result = CommonResult.failed("登录失败:" + ex.getMessage());
            resp.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().println(JsonUtil.toJsonString(result));
        });
        return loginFilter;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((req, resp, ex) -> {
                    resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                    resp.setStatus(HttpStatus.UNAUTHORIZED.value());
                    resp.getWriter().print("请认证后再处理");
                })
                .and()
                .logout()
                .logoutRequestMatcher(new OrRequestMatcher(
                        new AntPathRequestMatcher("/logout", HttpMethod.DELETE.name()),
                        new AntPathRequestMatcher("/logout", HttpMethod.GET.name())
                ))
                .logoutSuccessHandler((req, resp, auth) -> {
                    CommonResult<Object> result = CommonResult.success(auth.getPrincipal());
                    resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                    resp.setStatus(HttpStatus.OK.value());
                    resp.getWriter().println(JsonUtil.toJsonString(result));
                })
                .and()
                .csrf().disable();

        // at: 用来某个 filter 替换过滤器链中哪个 filter
        // before: 放在过滤器链中哪个 filter 之前
        // after: 放在过滤器链中那个 filter 之后
        http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
    }

}
